Chapter 8: Permissions

Currently, we allow anyone to access the API endpoint and list or create a todo. But this obviously shouldn’t be the

case as we only want registered users to call the API to read/create their own todos (which others don’t have access

to). So how do we ensure that only authenticated users can call the API and deny access to unauthenticated users?

Just add two lines in todobackend/api/views.py:

Modify Bold Code

from rest_framework import generics, permissions

from .serializers import TodoSerializer

from todo.models import Todo

class TodoListCreate(generics.ListCreateAPIView):

...

serializer_class = TodoSerializer

permission_classes = [permissions.IsAuthenticated]

...

With this, we specify that only authenticated and registered users have permission to call this API. Unauthenticated

users are not allowed to access it.

A slightly less strict style of permission would be to allow full access to authenticated users, but allow read-only

access to unauthenticated users. To do so, we specify the IsAuthenticatedOrReadOnly class. i.e.

Analyze Code

permission_classes = [permissions.IsAuthenticated]

There are other permissions like:

- IsAdminUser – only admins/superusers have access

- AllowAny – any user, authenticated or not, has full access

With permissions, we can grant or deny access for different classes of users to different parts of the API.

Test Your App

Now, go to localhost:8000/admin in your browser and log out of your account. Revisit localhost:8000/api/todos

and will see a message saying (fig. 1):

Figure 1

If log back in through the admin page and visit localhost:8000/api/todos, you will be able to see your todos now.